﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AteneoLibriBusinessLogic.Entities;
using AteneoLibri.Utility;

namespace AteneoLibri
{
    public partial class _Default : System.Web.UI.Page
    {
        User user = null;

        protected void Page_PreInit(object sender, EventArgs e)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (User.Identity.Name.Equals(System.Configuration.ConfigurationManager.AppSettings["AdminName"]))
                {
                    Page.MasterPageFile = "~/BackEnd/BackEndMasterPage.Master";
                }
                else
                {
                    Page.MasterPageFile = "~/Account/NewAccountMasterPage.Master";
                }                
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
            {                
                List<Book> books = service.getBooks().Where(x => !x.IsDeleted.HasValue || (x.IsDeleted.HasValue && !x.IsDeleted.Value)).ToList();

                int trimTitleLength = Convert.ToInt16(System.Configuration.ConfigurationManager.AppSettings["TrimTitleValue"]);

                books = books.Select(b => new Book { IdBook = b.IdBook, Title = Utility.Utility.TrimTitle(b.Title, trimTitleLength), Author = b.Author, SellingPrice = b.SellingPrice, UserName = b.UserName, InsertDate = b.InsertDate }).OrderByDescending(x => x.InsertDate).ToList();

                dlBooks.DataSource = books.Take(6);
                dlBooks.DataBind();

                dlBooksPortrait.DataSource = books.Take(3);
                dlBooksPortrait.DataBind();
            }

        }

        protected void btnDetails_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton button = sender as ImageButton;
            string idBook = button.CommandArgument;
            Response.Redirect("~/BookDetails.aspx?IdBook=" + idBook );
        }

    }
}
